package com.wish233.wiliwiliuser.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wish233.wiliwiliapi.domain.dto.UserDTO;
import com.wish233.wiliwilicommon.common.BaseResponse;
import com.wish233.wiliwilicommon.common.ErrorCode;
import com.wish233.wiliwilicommon.common.ResultUtils;
import com.wish233.wiliwilicommon.exception.BusinessException;
import com.wish233.wiliwilicommon.exception.ThrowUtils;
import com.wish233.wiliwiliuser.domain.dto.UserLoginRequest;
import com.wish233.wiliwiliuser.domain.dto.UserQueryRequest;
import com.wish233.wiliwiliuser.domain.dto.UserRegisterRequest;
import com.wish233.wiliwiliuser.domain.dto.UserUpdateRequest;
import com.wish233.wiliwiliuser.domain.po.User;
import com.wish233.wiliwiliuser.domain.vo.UserVO;
import com.wish233.wiliwiliuser.service.UserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author WHH
 * 用户登录注册相关接口
 */
@RestController
public class UserController {

    @Resource
    private UserService userService;

    /**
     * 用户登录
     * @param userLoginRequest
     * @param request
     * @return
     */
    @ApiOperation("用户登录")
    @PostMapping("/login")
    public BaseResponse<UserVO> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userLoginRequest.getUsername();
        String userPassword = userLoginRequest.getPassword();
        if (!StrUtil.isAllNotBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserVO userVO = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(userVO);
    }

    /**
     * 用户注册
     * @param userRegisterRequest
     * @return
     */
    @ApiOperation("用户注册")
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String username = userRegisterRequest.getUsername();
        String password = userRegisterRequest.getPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        if (!StrUtil.isAllNotBlank(username, password, checkPassword)) {
            return null;
        }
        long result = userService.userRegister(username, password, checkPassword);
        return ResultUtils.success(result);
    }

    /**
     * 用户登出
     * @return
     */
    @ApiOperation("用户登出")
    @PostMapping("/logout")
    @SaCheckLogin
    public BaseResponse<Boolean> userLogout() {
        StpUtil.logout();
        return ResultUtils.success(true);
    }

    @PostMapping("/sign")
    @SaCheckLogin
    public BaseResponse<Boolean> userSign() {
        return ResultUtils.success(userService.userSign());
    }

    @ApiOperation("查询用户信息")
    @GetMapping("/{id}")
    public BaseResponse<UserVO> getUserById(@PathVariable Long id) {
        if (id == null || id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserVO userVO = userService.getUserById(id);
        return ResultUtils.success(userVO);
    }

    @ApiOperation("查询用户信息(内部调用)")
    @GetMapping("/dto")
    public UserDTO getUserDTOById(@RequestParam Long id) {
        if (id == null || id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        return userService.getUserDTOById(id);

    }

    @PostMapping("/dto/batch")
    @ApiOperation("批量查询用户信息(内部调用)")
    Map<Long, UserDTO> getUserByIdBatch(@RequestBody Set<Long> userIds) {
        ThrowUtils.throwIf(CollectionUtil.isEmpty(userIds), new BusinessException(ErrorCode.PARAMS_ERROR));
        return userService.getUserByIdBatch(userIds);
    }

    @PostMapping("/dto/batch/list")
    @ApiOperation("批量查询用户信息(内部调用)")
    List<UserDTO> getUserByIdBatchSorted(@RequestBody Set<Long> userIds) {
        ThrowUtils.throwIf(CollectionUtil.isEmpty(userIds), new BusinessException(ErrorCode.PARAMS_ERROR));
        return userService.getUserByIdBatchSorted(userIds);
    }

    @ApiOperation("分页查询用户信息")
    @PostMapping("/list")
    public BaseResponse<List<UserVO>> listUserByPage(@RequestBody UserQueryRequest userQueryReques) {
        ThrowUtils.throwIf(userQueryReques == null, new BusinessException(ErrorCode.PARAMS_ERROR));
        int current = userQueryReques.getCurrent();
        int pageSize = userQueryReques.getPageSize();
        Page<User> page = userService.page(new Page<>(current, pageSize),
                userService.getQueryWrapper(userQueryReques));
        return ResultUtils.success(page.getRecords().stream().map(
                (user) -> BeanUtil.copyProperties(user, UserVO.class)).collect(Collectors.toList()));
    }

    @ApiOperation("更新用户信息")
    @PutMapping()
    public BaseResponse<Boolean> updateUser(@RequestBody UserUpdateRequest userUpdateRequest) {
        if (userUpdateRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = userService.updateUser(userUpdateRequest);
        return ResultUtils.success(result);
    }

    @ApiOperation("删除用户")
    @DeleteMapping("/{id}")
    public BaseResponse<Boolean> deleteUser(@PathVariable Long id) {
        if (id == null || id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = userService.deleteUser(id);
        return ResultUtils.success(result);
    }

}
